package edu.tsinghua.ddb.site;

import java.io.File;
import java.io.FileOutputStream;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Map.Entry;

import com.sun.rowset.CachedRowSetImpl;

import edu.tsinghua.ddb.data.LocalDataAccess;
import edu.tsinghua.ddb.dictionary.GD;
import edu.tsinghua.ddb.dictionary.GlobalDictionary;
import edu.tsinghua.ddb.main.console.MyLog;
import edu.tsinghua.ddb.main.swing.SitesMonitor;
import edu.tsinghua.ddb.util.Event;
import edu.tsinghua.ddb.util.TicToc;

public class SiteImp extends BasicSite {
	private static final long serialVersionUID = -7633591654117719396L;

	public SiteImp(String siteName) throws RemoteException {
		super(siteName);
		super.startListeningRMI();
	}

	@Override
	public CachedRowSetImpl query(String sqlString) throws RemoteException {
		try {
			return LocalDataAccess.query(sqlString);
		} catch (SQLException e) {
			throw new RemoteException(e.getMessage());
		}
	}

	@Override
	public int execute(String sqlString) throws RemoteException {
		MyLog.info(siteName + " loEx:" + sqlString);
		try {
			return LocalDataAccess.excute(sqlString);
		} catch (SQLException e) {
			throw new RemoteException(e.getMessage());
		}
	}

	@Override
	public void ping(String from) throws RemoteException {
		try {
			String me = SitePool.me.getName();
			if (from.equalsIgnoreCase(me)) {
				for (Entry<Site, SiteAttributes> sa : SitePool.sAttrMap
						.entrySet()) {
					Site s = sa.getKey();
					TicToc.tic();
					try {
						s.ping(from);
						long l = TicToc.toc();
						// MyLog.debug("RTT between " + this.getName() + " and "
						// + s.getName() + " = " + l);

						sa.getValue().rtt = l;
						SitesMonitor.refresh();
					} catch (java.rmi.ConnectException e) {

						MyLog.debug(this + " can not connect to "
								+ sa.getValue().name);
						Event.fire(Event.LOST_CONNECTION, sa.getValue().name);
					}
				}
			} else
				MyLog.info("ping from " + from);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void upload(byte[] cnt, String filePath) throws RemoteException {
		File f = new File(filePath);

		try {
			if (!f.exists()) {
				f.createNewFile();
			}
			f.deleteOnExit();
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(cnt);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void updateGD(GlobalDictionary gd) throws RemoteException {
		GD.replace(gd);
		execute("use " + siteName);
	}
}
